package org.coco24.pmstudio.widget

import com.badlogic.gdx.scenes.scene2d.Actor
import com.kotcrab.vis.ui.building.StandardTableBuilder
import com.kotcrab.vis.ui.util.adapter.AbstractListAdapter
import com.kotcrab.vis.ui.util.adapter.ArrayListAdapter
import com.kotcrab.vis.ui.widget.VisTextButton
import org.coco24.pmstudio.`interface`.SimpleWindowCallback
import org.coco24.pmstudio.util.UIUtils
import org.coco24.pmstudio.util.UIUtils.setOnChanged
import org.coco24.pmstudio.util.UIUtils.updateList
import org.coco24.pmstudio.window.NewWindow
import java.lang.IllegalStateException

class NamedOperationBar<ItemT, ViewT: Actor>(val adapter: ArrayListAdapter<ItemT, ViewT>, val callback: NamedOperationBarCallback<ItemT>): OperationBar<ItemT, ViewT>(adapter)
{
    val renameButton = VisTextButton("R")
    init
    {
        setOnChanged(addButton, Runnable {
            NewWindow("新建（内部名称）", object : SimpleWindowCallback {
                override fun onConfirmed(obj: Any)
                {
                    if(obj !is String) throw IllegalStateException()
                    if(obj.isBlank()) return
                    val item = callback.add(obj)
                    adapter.itemsChanged()
                    if(adapter.selectionMode != AbstractListAdapter.SelectionMode.DISABLED)
                    {
                        adapter.selectionManager.select(item)
                    }

                }
                override fun onCanceled()
                {
                }
            }).show(stage)
        })
        setOnChanged(renameButton, Runnable {
            adapter.selection.forEach {
                NewWindow("重命名（内部名称）", object : SimpleWindowCallback {
                    override fun onConfirmed(obj: Any)
                    {
                        if(obj !is String) throw IllegalStateException()
                        if(obj.isBlank()) return
                        adapter.selection.forEach {
                            callback.rename(it, obj)
                        }
                        UIUtils.updateList(adapter)
                    }
                    override fun onCanceled()
                    {
                    }
                }, callback.getName(it)).show(stage)
            }
        })
        setOnChanged(deleteButton, Runnable {
            if(adapter.selection.size == 0) return@Runnable
            updateList(adapter, Runnable {
                adapter.selection.forEach {
                    adapter.remove(it)
                }
            })
            callback.delete()

        })
        clear()
        add(StandardTableBuilder().append(addButton).append(renameButton).append(deleteButton).row().build())
        pack()
    }

    interface NamedOperationBarCallback<ItemT>
    {
        fun add(name: String): ItemT
        fun rename(item: ItemT, name: String)
        fun delete()
        fun getName(item: ItemT): String
    }
}